/**
 * Dashboard.Main
 * The main dashboard object
 * - handles comments and likes
 * - handles loading or refreshing surfaces
 *
 * @author Seth
 * @version 1.2
 */
Dashboard.Main = function() {
	var open = false,
		max = 200,
		user = 0,
		page = 1,
		c_page = -1,
		more = 1,
		r_more = 0,

	// syncronize the blanks
	_sync = function(x) {
		if(x != undefined) {
			var a = x.find('div.ratings').html().trim(),
				b = x.find('div.comments').html().trim(),
				c = x.find('div.post:visible');

			if(a.length > 0 || b.length > 0 || c.length > 0) x.find('div.relax').show();
			else x.find('div.relax').hide();
		}

		Dashboard.Privacy.sync();

	// automatically refresh entries surfaces (every x seconds 10 entries, cycle between them if more)
	}, _refr = function() {
		// refresh data
		window.setInterval(function() {
			var a = $('div.entries > div.entry'),
				d = [],
				p = 10,
				o = [],
				x = 0,
				y = p;

			// populate d
			if(a.length == 1) d.push(a.data('id'));
			else {
				a.each(function(k, v) {
					d.push($(v).data('id'));
				});
			}

			// group up for queue
            for (var i = 1; i <= Math.ceil(d.length/p); i++) {
                o[i] = d.slice(x, y);
                x += p;
                y += p;
            }

            // cycle between
            if(o[r_more + 1]) r_more++;
            else r_more = 1;

            // perform stealthed refresh request
	    	Petolio.ajax({
				url: 'dashboard/refresh',
				type: 'post',
				data: {id: o[r_more], surface: 'all', page: Dashboard.store().location == 'view' ? c_page : 0},
				cache: false,
				success: function (x) {
					$.each(x.data, function(k, v) {
						var e = $('div.entry:data("id='+ k +'")');

						// update surfaces for every entry
						e.find('div.links').html(v.links);
						e.find('div.ratings').html(v.ratings);
						e.find('div.comments').html(v.comments);

						// sync every entry
						_sync(e);
					});
				},
				error: function() {}
			});
		}, 30629); // ~30 seconds

	// check for new entries (run every x seconds, depending on the ajax request load time)
	}, _newr = function() {
		window.setTimeout(function(){
			var q = $('div.new_entries'),
				t = $('div.entries > div.new_start'),
				a = q.find('a'),
				sw = Dashboard.store().location == 'news' ? 1 : (Dashboard.store().location == 'all' ? 2 : 0);

            // perform stealthed refresh request
	    	Petolio.ajax({
				url: 'dashboard/new',
				type: 'post',
				data: {x: user, time: t.data('timestamp'), sw: sw},
				cache: false,
				success: function (x) {
					// at least 1 new entry?
					if(x.count > 0) {
						// show up
						q.fadeIn();
						var c = a.find('span');

						// update count
						if(c.length > 0) a.html(_translate('new_many').replace('%s', '<span>' + (parseInt(c.html()) + x.count) + '</span>'));
						else {
							// set count
							if(x.count == 1) a.html(_translate('new_one').replace('%s', '<span>1</span>'));
							else a.html(_translate('new_many').replace('%s', '<span>' + x.count + '</span>'));
						}
					}

					// update last checked and loop
					t.data('timestamp', x.time);
					_newr();
				},
				error: function() {
					_newr();
				}
			});
		}, 45654); // ~45 seconds

	// show loading
	}, _load = function(x) {
		var q = x.find('div.post:visible'),
			t = q.length > 0 && (q.find('textarea').val() == _translate('blank') || q.find('textarea').val().length == 0);

		// attach our disabler
		$('div.disabler').css({
			top: x.position().top,
			height: t ? x.height() - q.height() + 3 : x.height()
		}).delay(100).animate({opacity: 0.50}, 'fast');

	// hide loading
	}, _unload = function(x) {
		$('div.disabler').delay(100).animate({opacity: 0}, 'fast', function(){
			$(this).css({
				top: 0,
				height: 0
			});
		});

		// add rating handler
	}, _subscription_add = function() {
		var q = $(this),
			p = q.closest('div.entry').data('identity'),
			s = p.split('|');

		_load(q.closest('div.entry'));
    	Petolio.ajax({
			url: 'social/create',
			type: 'post',
			data: {id: s[0], scope: s[1], plugin: 'subscriptions'},
			cache: false,
			success: function (x) {
				_subscription_refresh(q.closest('div.entry'));
			}
		});

	// delete rating handler
	}, _subscription_delete = function() {
		var q = $(this),
			p = q.closest('div.entry').data('identity'),
			s = p.split('|');

		_load(q.closest('div.entry'));
		Petolio.ajax({
			url: 'social/delete',
			type: 'post',
			data: {x: q.data('id'), id: s[0], scope: s[1], plugin: 'subscriptions'},
			cache: false,
			success: function (x) {
				_subscription_refresh(q.closest('div.entry'));
			}
		});

    // refresh rating surface
	}, _subscription_refresh = function(q) {
		var l = q.find('div.links');

		// refresh data
    	Petolio.ajax({
			url: 'dashboard/refresh',
			type: 'post',
			data: {id: q.data('id'), surface: 'links'},
			cache: false,
			success: function (x) {
				l.html(x.data.links);

				_sync(q);
				_unload(q);
			}
		});

	// add rating handler
	}, _rating_add = function() {
		var q = $(this),
			p = q.closest('div.entry').data('identity'),
			s = p.split('|'),
			url = '<a href="'+ unescape(_translate('entry_url')).replace('{id}', s[0]) +'">{entries}</a>';

		_load(q.closest('div.entry'));
    	Petolio.ajax({
			url: 'social/create',
			type: 'post',
			data: {id: s[0], scope: s[1], plugin: 'ratings', label: '{ignore}', url: url, owner: s[2]},
			cache: false,
			success: function (x) {
				_rating_refresh(q.closest('div.entry'));
			}
		});

    // delete rating handler
	}, _rating_delete = function() {
		var q = $(this),
			p = q.closest('div.entry').data('identity'),
			s = p.split('|');

		_load(q.closest('div.entry'));
    	Petolio.ajax({
			url: 'social/delete',
			type: 'post',
			data: {x: q.data('id'), id: s[0], scope: s[1], plugin: 'ratings'},
			cache: false,
			success: function (x) {
				_rating_refresh(q.closest('div.entry'));
			}
		});

    // refresh rating surface
	}, _rating_refresh = function(q) {
		var l = q.find('div.links'),
			d = q.find('div.ratings');

		// refresh data
    	Petolio.ajax({
			url: 'dashboard/refresh',
			type: 'post',
			data: {id: q.data('id'), surface: 'ratings'},
			cache: false,
			success: function (x) {
				l.html(x.data.links);
				d.html(x.data.ratings);

				_sync(q);
				_unload(q);
			}
		});

    // view likes handler
	}, _rating_view = function(a, b) {
		var q = b ? b : this,
			p = $(q).closest('div.entry').data('identity'),
			s = p.split('|');

		Petolio.showLoading();
    	Petolio.ajax({
			url: 'social/misc',
			type: 'post',
			data: {id: s[0], scope: s[1], plugin: 'ratings', page: page},
			cache: false,
			success: function (x) {
				Petolio.hideLoading();
				Social.Ratings.likes(x, _translate, function() {
					_rating_pagination(this, q);
				}, function(){
					page = 1;
				});
			}
		});

	// pagination handle
	},	_rating_pagination = function(e, q) {
		var p = parseInt($(e).data('id'));

		// only numbers allowed
		if(!isNaN(p))
			page = p;

		_rating_view(function(){}, q);

	// add comment handler
	}, _comment_add = function(e) {
		var t = $(e.target),
			e = t.closest('div.entry'),
			p = e.find('div.post'),
			x = open != false ? $('div.entry:data("id='+ open +'")').find('div.post') : false;

		if(x && (x.find('textarea').val() == _translate('blank') || x.find('textarea').val().length == 0)){
			x.find('textarea').removeClass('error');
			x.find('textarea').addClass('normal');
			x.hide();
		}
		open = e.data('id');

		p.show();
		p.find('textarea').focus();

		_sync(e);
		return false;

	// delete comment handler
	}, _comment_delete = function() {
		var q = $(this),
			c = q.closest('div.entry'),
			p = c.data('identity'),
			s = p.split('|');

		// confirm first
		Petolio.showConfirm(_translate('delete_comment'), function() {
			_load(c);
	    	Petolio.ajax({
				url: 'social/delete',
				type: 'post',
				data: {x: q.parent().data('id'), id: s[0], scope: s[1], plugin: 'comments'},
				cache: false,
				success: function (x) {
					var p = Dashboard.store().location == 'view' ? c_page : 0;
					_comment_refresh(c, p);
				}
			});
		});

	// save comment
	}, _save_comment = function(p) {
		var q = p.data('identity');
			s = q.split('|'),
			z = p.find('textarea').val(),
			id = p.data('id'),
			url = '<a href="'+ unescape(_translate('entry_url')).replace('{id}', id) +'">{entries}</a>';

		// sync
		_sync(p);

		// ajax req
		_load(p);
    	Petolio.ajax({
			url: 'social/create',
			type: 'post',
			data: {id: s[0], scope: s[1], plugin: 'comments', comment: z, label: '{ignore}', url: url, owner: s[2]},
			cache: false,
			success: function (x) {
				_comment_refresh(p, Dashboard.store().location == 'view' ? -1 : 0);
			}
		});

    // refresh comments surface
	}, _comment_refresh = function(q, p) {
		var l = q.find('div.links'),
			d = q.find('div.comments'),
			page = p || 0;

		// refresh data
    	Petolio.ajax({
			url: 'dashboard/refresh',
			type: 'post',
			data: {id: q.data('id'), surface: 'comments', page: page},
			cache: false,
			success: function (x) {
				l.html(x.data.links);
				d.html(x.data.comments);

				_sync(q);
				_unload(q);
			}
		});

    // comment pagination
	}, _comment_pagination = function() {
		var q = $(this),
			p = parseInt(q.data('page'));

		// only numbers allowed
		if(!isNaN(p))
			c_page = p;

		// refresh surface
		_load(q.closest('div.entry'));
		_comment_refresh(q.closest('div.entry'), c_page);

	// textarea focus
	},	_focus = function() {
		if($(this).val() == _translate('blank'))
			$(this).val('');

	// textarea blur
	},	_blur = function() {
		if(!$(this).val())
			$(this).val(_translate('blank'));

	// textarea limit
	},	_limit = function(e) {
		// overwrite
		$(this).removeClass('error');
		$(this).addClass('normal');

		// on enter
		var code = (e.keyCode ? e.keyCode : e.which);
		if(code == 13) {
			$(this).val($(this).val().trim());
			if($(this).val().length == 0) {
				$(this).removeClass('normal');
				$(this).addClass('error');

				return false;
			}

			$(this).blur();
			$(this).closest('div.entry').find('div.post').hide();

			_save_comment($(this).closest('div.entry'));
			$(this).val('');
		}

		// get count
		var count = $(this).parent().find('[class="comment_count"]');

		// limit chars
		if ($(this).val().length > max) {
		    $(this).val($(this).val().substring(0, max));
		    this.scrollTop = this.scrollHeight;
		} else
		    count.html(max - $(this).val().length);

	// events binder
	}, _bind = function() {
		// delete entry
		$("div.entries").delegate('a[name="entry_delete"]', 'click', _entry_delete);

		// subscribe events
		$("div.entries").delegate('a[name="subscription_add"]', 'click', _subscription_add);
		$("div.entries").delegate('a[name="subscription_remove"]', 'click', _subscription_delete);

		// rating events
		$("div.entries").delegate('a[name="rating_add"]', 'click', _rating_add);
		$("div.entries").delegate('a[name="rating_remove"]', 'click', _rating_delete);
		$("div.entries").delegate('a[name="rating_view"]', 'click', _rating_view);

		// comment events
		$("div.entries").delegate('a[name="comment_add"]', 'click', _comment_add);
		$("div.entries").delegate('a[name="comment_delete"]', 'click', _comment_delete);
		$("div.entries").delegate('a:data("page")', 'click', _comment_pagination);

		// post comment events
		$("div.entries").delegate('[name="comment_body"]', 'focus', _focus);
		$("div.entries").delegate('[name="comment_body"]', 'blur', _blur);
		$("div.entries").delegate('[name="comment_body"]', 'keyup', _limit);
		$("div.entries").delegate('[name="comment_body"]', 'keydown', _limit);

		// stop propagation & auto-close on any click
		$("div.entries").delegate('div.entries > div.entry div.post > div > div', 'click', function() { return false; });
		$("html").delegate('body', 'click', function() {
			$('div.entry').find('div.post').each(function(k, v) {
				var x = $(v);
				if(x.find('textarea').val() == _translate('blank') || x.find('textarea').val().length == 0) {
					x.find('textarea').removeClass('error');
					x.find('textarea').addClass('normal');
					x.hide();
					_sync(x.closest('div.entry'));
				}
			});
		});

		// entry share
		$("div.entries").delegate('a[name="entry_share"]', 'click', _entry_share);

		// new & more
		$("div.new_entries").delegate('a[name="new"]', 'click', _reload_dashboard);
		$("div.entries").delegate('a[name="more"]', 'click', _load_more);

	// share the entry
	}, _entry_share = function() {
		var q = $(this),
			p = q.closest('div.entry').data('id');

		// init share
		Dashboard.Share.init(p);

	// delete the entry
	}, _entry_delete = function() {
		var d = $(this).closest('div.entry'),
			i = $('div.entry').index(d);

		// confirm first
		Petolio.showConfirm(_translate('delete_entry'), function() {
			// make the delete request
	    	Petolio.ajax({
				url: 'dashboard/delete',
				type: 'post',
				data: {x: d.data('id')},
				cache: false,
				success: function (x) {
					// remove from dom
					d.prev('div.delimiter').remove();
					if(i == 0)
						d.next('div.delimiter').remove();
					d.remove();

					// no more entries? reload the dashboard
					if($('div.entries > div.entry').length == 0)
						_reload_dashboard();
				}
			});
		});

	// load more events
	}, _load_more = function() {
		var d = $("div.entries"),
			sw = Dashboard.store().location == 'news' ? 1 : (Dashboard.store().location == 'all' ? 2 : 0);

		// increment
		more = more + 1;

		// show loading
		d.find('div.more > a').hide();
		d.find('div.more > span').show();

		// load more data
    	Petolio.ajax({
			url: 'dashboard/more',
			type: 'post',
			data: {x: user, more: more, sw: sw},
			cache: false,
			success: function (x) {
				// remove more div
				d.find('div.more').remove();

				// if data, append
				if(x.count > 0) {
					if($('div.entries > div.entry').length > 0)
						d.append('<div class="delimiter"></div>');

					d.append(x.data);
					_sync();
				}
			}
		});

   	// reload dashboard
	}, _reload_dashboard = function() {
		var d = $("div.entries"),
			sw = Dashboard.store().location == 'news' ? 1 : (Dashboard.store().location == 'all' ? 2 : 0);

		// load new
		$('div.new_entries > a').hide();
		$('div.new_entries > span').show();

		// reset more
		more = 1;

		// trigger load
		$("body").trigger({
			type: "Dashboard",
			loading: true
		});

		// reload data
    	Petolio.ajax({
			url: 'dashboard/more',
			type: 'post',
			data: {x: user, more: 1, sw: sw},
			cache: false,
			success: function (x) {
				// trigger unload
				$("body").trigger({
					type: "Dashboard",
					loading: false
				});

				// reset new
				$('div.new_entries > a').html('');
				$('div.new_entries > a').show();
				$('div.new_entries > span').hide();
				$('div.new_entries').hide();

				// if data, update
				d.html(x.data);
				_sync();
			}
		});

    // translate
	}, _translate = function(i) {
		return Dashboard.Translate.init(i);

	// constructor
	}, __construct = function(u) {
		_bind();
		_sync();
		_refr();
		_newr();

		// set user
		user = u;

		// initialize support for ratings
		Social.load('ratings');
	};

	// public
	return {
		init: __construct,
		reload: _reload_dashboard,
		load: _load,
		unload: _unload
	};
}();